/**
 * @create 2022-03-30
 * @desc SideMenu
 */

import { FC, useEffect, useMemo, useState } from 'react';
import { Menu } from 'antd';
import { RouteConfig } from 'react-router-config';
import { Link } from 'react-router-dom';
import { IconComp } from '@src/components';
import { routerConfig } from '../routers';
import { useCurRoutes } from '../common/hooks';

export const SideMenu: FC = () => {
  const matchCurRoutes = useCurRoutes();
  const [selectKey, setSelectKey] = useState<string[]>();
  const [openKeys, setOpenKeys] = useState<string[]>();

  const matchRouteKeys = useMemo(
    () => matchCurRoutes.map((item) => item.path as string),
    [matchCurRoutes],
  );

  useEffect(() => {
    const select = matchRouteKeys[matchRouteKeys.length - 1];
    const open = matchRouteKeys.slice(0, -1);

    setSelectKey([select]);
    setOpenKeys(open);
  }, [matchRouteKeys]);

  const getMenuItem = (menus: RouteConfig[]) => {
    return menus
      .filter((item) => item?.meta?.displayOnTree)
      .map((menu) => {
        const { meta } = menu;
        const routePath = menu.path as string;
        if (
          'routes' in menu &&
          Array.isArray(menu.routes) &&
          menu.routes.some((item) => item?.meta?.displayOnTree)
        ) {
          return (
            <Menu.SubMenu
              key={routePath}
              title={meta?.title}
              icon={meta?.icon && <IconComp iconKey={meta?.icon} />}
            >
              {getMenuItem(menu.routes)}
            </Menu.SubMenu>
          );
        }

        return (
          <Menu.Item key={routePath} icon={meta?.icon && <IconComp iconKey={meta?.icon} />}>
            <Link to={routePath}>{meta?.title}</Link>
          </Menu.Item>
        );
      });
  };

  return (
    <div className="h-full flex flex-col">
      <Menu
        mode="inline"
        selectedKeys={selectKey}
        openKeys={openKeys}
        onClick={({ key }) => setSelectKey([key])}
        onOpenChange={(keys) => setOpenKeys(keys)}
      >
        {getMenuItem(routerConfig)}
      </Menu>
    </div>
  );
};
